package com.laf.common.utils.mq;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class RabbitMqHelper {


    private final RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     * @param exchange 路由名
     * @param routingKey 路由键
     * @param msg 消息
     */
    public void sendMessage(String exchange, String routingKey, Object msg) {
        log.info("发送消息：exchange:{},routingKey:{},msg:{}", exchange, routingKey, msg);
        rabbitTemplate.convertAndSend(exchange, routingKey, msg);
    }

    /**
     * 发送延迟消息
     * @param exchange 路由名
     * @param routingKey 路由键
     * @param msg 消息
     * @param delay
     */
    public void sendDelayMessage(String exchange, String routingKey, Object msg, long delay) {
        log.info("发送消息：exchange:{},routingKey:{},msg:{} , delay: {}" , exchange, routingKey, msg ,delay);
        rabbitTemplate.convertAndSend(exchange, routingKey, msg, message -> {
             // message.getMessageProperties().setDelayLong(delay);
            message.getMessageProperties().setDelay(Integer.valueOf(delay+""));
            return message;
        });
    }

    /**
     * 发送带有确认消息， （ 发送这个消息如果消息异常触发消息重试机制 ）
     * @param exchange 路由名
     * @param routingKey 路由键
     * @param msg 消息
     * @param maxRetries 最大重试次数
     */
    public void sendMessageWithConfirm(String exchange, String routingKey, Object msg, int maxRetries) {
        log.info("发送消息：exchange:{},routingKey:{},msg:{} , maxRetries: {}" , exchange, routingKey, msg ,maxRetries);
        rabbitTemplate.convertAndSend(exchange,routingKey,msg,message -> {
            // x-max-delivery  设置最大重试次数
            message.getMessageProperties().setHeader("x-max-delivery",maxRetries);
            return message;
        });
    }
}
